<script setup name="AnnualFeeYjf">
import { ElDatePicker, ElMessageBox } from 'element-plus'
import Message from 'vue-m-message'
import useMessageBox from '@/utils/useMessageBox.js'
import YearFeeDetailModal from '@/views/system/annualFee/components/YearFeeDetailModal.vue'
import { formatDate } from '@/utils/dayjs.js'
import annualFeeService from '@/api/annualFee/index.js'
import SvgIcon from '@/components/SvgIcon/index.vue'
import Toolbar from '@/components/Toolbar/Toolbar.vue'
import { tableCheckChane } from '@/utils/index.js'
import { yearFeeSearchConfig, yearFeeTableColumns } from '@/views/system/annualFee/yearFeeConfig.js'

const { proxy } = getCurrentInstance()
const pagerConfig = ref({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
const ids = ref([])
const tableData = ref([])
const queryParam = ref({
  feeNode: '0',
})
const annualFeeId = ref('')
const yearFeeDetailModalVisible = ref(false)

const searchConfig = ref(getSearchConfig())
const detailParams = ref({})
onMounted(() => {
  getList()
})

function getSearchConfig() {
  return yearFeeSearchConfig.map((item) => {
    const newItem = { ...item }
    if (item.field !== 'feeNode') {
      // newItem.default = undefined; // 直接设置 default 属性为 undefined
    }
    else {
      newItem.default = queryParam.value.feeNode
    }
    return newItem
  })
}
function getList() {
  const params = {
    pageSize: pagerConfig.value.pageSize,
    pageNum: pagerConfig.value.currentPage,
    status: '1',
    ...queryParam.value,
  }
  annualFeeService.list(params).then((res) => {
    const { rows, total } = res
    pagerConfig.value.total = total
    tableData.value = rows
  })
}

function handleView(row) {
  detailParams.value = row
  yearFeeDetailModalVisible.value = true
}

function handlePayByCustomerSelf(data) {
  const idArray = data?.annualfeeId || ids.value.join(',')
  const date = formatDate(new Date())
  const datePicker = h(ElDatePicker, {
    'class': 'w-full!',
    'placeholder': '请选择日期',
    'valueFormat': 'YYYY-MM-DD',
    'modelValue': date,
    'onUpdate:modelValue': (e) => {
      if (datePicker.component?.props) {
        datePicker.component.props.modelValue = e
      }
    },
  })
  ElMessageBox({
    title: '实际缴费时间',
    message: datePicker,
    customClass: 'custom-message-box',
  }).then((res) => {
    if (res === 'confirm') {
      annualFeeService.payByCustomerSelf(idArray, { paymentTime: date }).then((res) => {
        const code = res.code
        if (code === 200) {
          Message.success('提交成功')
          getList()
        }
      })
    }
  })
}

function handlePageChange({ currentPage, pageSize }) {
  pagerConfig.value.currentPage = currentPage
  pagerConfig.value.pageSize = pageSize
  getList()
}

function handleCheckChange(data) {
  ids.value = tableCheckChane(data, 'annualfeeId', ids.value)
}

function handleExport() {
  proxy.download('', { ...queryParam.value, exportIds: ids.value.join(',') }, `_${new Date().getTime()}.xlsx`)
}

function handleSearch(params) {
  queryParam.value = params
  // console.log(searchConfig.value)
  // console.log(queryParam.value)
  getList()
}

function handleTabChange(name) {
  queryParam.value = {}
  pagerConfig.value.currentPage = 1
  pagerConfig.value.pageSize = 10
  queryParam.value.feeNode = name
  searchConfig.value = getSearchConfig()
  // searchConfig.value = searchConfig.value.map((item) => {
  //   item.default = ''
  //   if (item.field === 'feeNode') {
  //     item.default = name
  //   }
  //   return item
  // })
  getList()
}

function handleEditRemark(row) {
  const { remark } = row
  ElMessageBox.prompt('请输入备注', '提示', {
    inputType: 'textarea',
    inputValue: remark,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        annualFeeService.update({ ...row, remark: instance.inputValue, isUpdateRemark: '1' }).then((res) => {
          const code = res.code
          if (code === 200) {
            Message.success('修改成功')
            done()
          }
        })
      }
      else {
        done()
      }
    },
  }).then((res) => {
    getList()
  })
}

function handleGenerateAPaymentNote() {
  useMessageBox({
    title: '提示',
    description: `确认要生成${ids.value.length}条缴费单？`,
    icon: 'color-wait',
  }).then((res) => {
    if (res) {
      annualFeeService.insert(ids.value.join(',')).then((res) => {
        if (res.code === 200) {
          Message.success('生成成功')
          getList()
        }
      })
    }
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="">
      <el-tabs v-model="queryParam.feeNode" @tab-change="handleTabChange">
        <el-tab-pane label="办登" name="0" />
        <el-tab-pane label="年费" name="1" />
        <el-tab-pane label="滞纳金" name="2" />
        <el-tab-pane label="恢复金" name="3" />
      </el-tabs>
      <SearchBar :search-config="searchConfig" @search="handleSearch" />
    </el-card>
    <el-card shadow="never" class="mt-2">
      <Toolbar>
        <el-button
          v-hasPermi="['system:annualFeeJfd:add']"
          type="primary"
          class="el-gradient-purple"
          :disabled="ids.length === 0"
          @click="handleGenerateAPaymentNote()"
        >
          生成缴费单
          <SvgIcon name="material-symbols-light:order-approve" type="iconify" class="text-[#562DFF] bg-white w-4 h-4 rounded-full ml-2 " />
        </el-button>
        <el-button
          v-hasPermi="['system:annualFee:payByCustomerSelf']"
          type="primary"
          class="el-gradient-pink"
          :disabled="ids.length === 0"
          @click="handlePayByCustomerSelf()"
        >
          批量客户已缴
          <span class="bg-white w-4 h-4 rounded-full ml-2 ">
            <SvgIcon name="btn-payByCustomerSelf" class-name="text-[#FE1FC4] text-[11px]" />
          </span>
        </el-button>
        <el-button
          v-hasPermi="['system:annualFee:export']"
          type="warning"
          class="el-gradient-warning"
          @click="handleExport()"
        >
          导出
          <el-icon class="el-icon--right">
            <FolderAdd />
          </el-icon>
        </el-button>
      </Toolbar>
      <vxe-grid
        :row-config="{
          keyField: 'annualfeeId',
        }"
        :data="tableData"
        :columns="yearFeeTableColumns"
        :pager-config="pagerConfig"
        header-cell-class-name="headerCellClass"
        max-height="500px"
        @page-change="handlePageChange"
        @checkbox-all="handleCheckChange"
        @checkbox-change="handleCheckChange"
      >
        <template #actions="{ row }">
          <el-button
            v-hasPermi="['system:annualFee:query']"
            size="small"
            text
            @click="handleView(row)"
          >
            查看
          </el-button>
          <el-button
            v-hasPermi="['system:annualFee:edit']"
            size="small"
            text
            type="primary"
            @click="handleEditRemark(row)"
          >
            修改备注
          </el-button>
          <el-popover
            placement="bottom" trigger="click"
            width="auto"
          >
            <template #reference>
              <el-button text type="primary" size="small">
                更多
                <el-icon class="el-icon--right">
                  <ArrowDownBold />
                </el-icon>
              </el-button>
            </template>
            <div class="flex divide-x">
              <span v-hasPermi="['system:annualFee:payByCustomerSelf']">
                <el-button
                  size="small"
                  text
                  type="success"
                  @click="handlePayByCustomerSelf(row)"
                >
                  客户已缴
                </el-button>
              </span>
              <span v-if="!row.deadline && row.feeNode === '3'">
                <el-button
                  v-hasPermi="['system:annualFee:edit']"
                  size="small"
                  type="primary"
                  text
                >
                  上传
                </el-button>
              </span>
            </div>
          </el-popover>
        </template>
      </vxe-grid>
    </el-card>
    <YearFeeDetailModal
      v-model:visible="yearFeeDetailModalVisible"
      :detail-params="detailParams"
    />
  </div>
</template>

<style lang="scss">
.custom-message-box{
  .el-message-box__message{
    width:100%;
  }
}
</style>
